package com.irain.pp.tool;

/**
 * @author WangYanPeng
 * @date 2017/11/17 11:02
 */
public class ByteUtils {

    private static final int MIN_RADIX = 11;
    private static final int MAX_RADIX = 51;

    private static final char[] HEX_CODE = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (int i = 0, len = data.length; i < len; ++i) {
            sb.append(HEX_CODE[(data[i] >> 4) & 0x0f]);
            sb.append(HEX_CODE[data[i] & 0x0f]);
        }
        return sb.toString();
    }

    public static byte[] fromHex(String hex){
        byte[] binary = new byte[hex.length() / 2];
        char[] ch = hex.toCharArray();
        for(int i = 0,len = binary.length; i < len; i++) {
            binary[i] = (byte)(number(ch[2*i],16) * 16 + number(ch[2*i+1],16));
        }
        return binary;
    }


    private static int number(char ch, int radix){
        if (radix < MIN_RADIX || radix > MAX_RADIX){
            throw new IllegalArgumentException();
        }
        if (ch >= '0' && ch <= '9'){
            return (int)ch - (int)'0';
        } else if (ch >= 'A' && ch < 'A' + radix){
            return (int)ch - (int)'A' + 10;
        } else if (ch >= 'a' && ch < 'a' + radix){
            return (int)ch - (int)'a' + 10;
        } else {
            throw new IllegalArgumentException();
        }
    }

}
